#define _CRT_SECURE_NO_WARNINGS 1

#include"game.h"

//初始化成空格棋盘函数
void init_board(char board[ROW][COL], int row, int col)
{
	for (int i = 0;i < ROW;i++)
	{
		for (int j = 0;j < COL;j++)
		{
			board[i][j] = ' ';
		}
	}
}

//打印棋盘函数
void print_board(char board[ROW][COL], int row, int col)
{
	for (int i = 0;i < row;i++)
	{
		//打印数据和竖线
		for (int j = 0;j < col;j++)
		{
			printf(" %c ", board[i][j]);
			if (j < col - 1)
				printf("|");
		}
		printf("\n");
		//打印横线
		if (i < row - 1)//比行少一段
		{
			for (int j = 0;j < col;j++)
			{
				printf("---");  //和列一样
				if (j < col - 1)
				{
					printf("|");//比列少一个
				}
			}
			printf("\n");
		}
	}
}

//玩家下棋函数
void player_move(char board[ROW][COL], int row, int col)
{
	int x = 1, y = 1;
	printf("请输入你下的坐标(行 列,空格分开):\n");
	while(1)
	{
		scanf("%d %d", &x, &y);
		if (x >= 1 && x <= row && y >= 1 && y <= col)
		{
			if (board[x - 1][y - 1] == ' ')
			{
				board[x - 1][y - 1] = '*';
				printf("玩家下:\n");
				break;
			}
			else
			{
				printf("坐标已被占用,请重新输入:\n");
			}
		}
		else
		{
			printf("坐标非法,重新输入:\n");
		}
	}
}

//电脑随机下棋函数
void computer_move(char board[ROW][COL], int row, int col)
{
	printf("电脑下:\n");
	int x = 1, y = 1;
	while(1)
	{
		x = rand() % row;
		y = rand() % col;
		if (board[x][y] == ' ')
		{
			board[x][y] = '#';
			break;
		}
	}
}

//判断棋盘是否满函数(平局)(在判断输赢函数内使用)
int is_full(char board[ROW][COL], int row, int col)
{
	for (int i = 0;i < row;i++)
	{
		for (int j = 0;j < col;j++)
		{
			if (board[i][j] == ' ')
			{
				return 0;
			}
		}
	}
	return 1;
}

//判断输赢/平局函数
char is_win(char board[ROW][COL], int row, int col)
{
	//判断行
	for (int i = 0; i < row; i++)
	{
		if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][1] != ' ')
		{
			return board[i][1];
		}
	}
	//判断列
	for (int i = 0; i < col; i++)
	{
		if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[1][i] != ' ')
		{
			return board[1][i];
		}
	}
	//两条对角线
	if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[1][1] != ' ')
	{
		return board[1][1];
	}
	if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[1][1] != ' ')
	{
		return board[1][1];
	}

	//判断平局
	if (is_full(board, row, col) == 1)//判断棋盘是否满函数
	{
		return 'g';
	}

	//继续
	return 'r';
}